package com.axonactive.yolo.validation;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.axonactive.yolo.domain.User;
import com.axonactive.yolo.domain.UserEmail;
import com.axonactive.yolo.dto.UserParameters;
import com.axonactive.yolo.service.interfaces.UserEmailService;
import com.axonactive.yolo.service.interfaces.UserService;
import com.axonactive.yolo.util.EncryptDecrypt;
import com.axonactive.yolo.util.Utils;

@Component
public class UserProfileValidator implements Validator {
	private static final Logger LOGGER = Logger.getLogger(UserProfileValidator.class);

	@Autowired
	private UserEmailService userEmailService;

	@Autowired
	private UserService userService;

	@Override
	public boolean supports(Class<?> clazz) {
		return UserParameters.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		UserParameters userParams = (UserParameters) target;

//		ValidationUtils.rejectIfEmpty(errors, "firstName", "firstName.notnull");
//		ValidationUtils.rejectIfEmpty(errors, "lastName", "lastName.notnull");
//		ValidationUtils.rejectIfEmpty(errors, "addEmailSecondary",
//				"secondary.email.invalid");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "gender",
				"gender.notnull");
		// validate FirstName
		if (userParams.getFirstName().trim().length() > 50) {
			errors.rejectValue("firstName", "firstName.outOfRange");
		} else if (!Utils.isValidName(userParams.getFirstName().trim())) {
			errors.rejectValue("firstName", "firstName.invalid");
		}
		// validate LastName
		if (userParams.getLastName().trim().length() > 50) {
			errors.rejectValue("lastName", "lastName.outOfRange");
		} else if (!Utils.isValidName(userParams.getLastName().trim())) {
			errors.rejectValue("lastName", "lastName.invalid");
		}
		// validate phone
		if (!"".equals(userParams.getPhone().trim()) 
				&& !Utils.isValidPhoneNUmber(userParams.getPhone().trim())) {
			errors.rejectValue("phone", "phone.invalid");
		}
		// validate DOB
		if (!"".equals(userParams.getDateOfBirth())) {
			try {
				Date birth = new SimpleDateFormat("yyyy-MM-dd")
						.parse(userParams.getDateOfBirth().trim());
				if (birth.getTime() > (new Date()).getTime()) {
					errors.rejectValue("dateOfBirth", "DOB.dateInFuture");
				}
			} catch (ParseException e) {
				LOGGER.error("UserProfileValidator class validate error",e);
			}
		}
		// validate newPassword
		User user = userService.findById(userParams.getUserId());
		String newPass = userParams.getNewPassword();
		String curPass = userParams.getCurrentPassword();
		String confirm_pass = userParams.getConfirmPassword();
		String tempPass = user.getPassword();
		if (userParams.getNewPassword().length() > 50) {
			errors.rejectValue("newPassword", "newPassword.outOfRange");
		}
		if (!"".equals(newPass) || !"".equals(curPass)) {
			LOGGER.info(curPass);
			LOGGER.info(tempPass);
			if (!"".equals(curPass) 
					&& !tempPass.equals(EncryptDecrypt.encryptMD5(curPass))) {
				errors.rejectValue("currentPassword",
						"current.password.notmatch");
			} else if (!newPass.equals(confirm_pass)) {
				errors.rejectValue("confirmPassword",
						"confirm.password.notmatch");
			} else if (tempPass.equals(EncryptDecrypt.encryptMD5(newPass))) {
				errors.rejectValue("newPassword", "new.password.existed");
			} else if (!Utils.isValidPassword(newPass)) {
				errors.rejectValue("newPassword", "new.password.invalid");
			}
		}
		// validate EmailSecondary
		LOGGER.info(userParams.getAddEmailSecondary());
		if (userParams.getAddEmailSecondary() != null) {
			LOGGER.info("do here !");
			for (int i = 0; i < userParams.getAddEmailSecondary().size(); i++) {
				// valid format
				if ("".equals(userParams.getAddEmailSecondary().get(i).trim())) {
					errors.rejectValue("addEmailSecondary",
							"secondary.email.invalid");
				}
				if (!"".equals(userParams.getAddEmailSecondary().get(i).trim())
						&& !Utils.isValidEmail(userParams
								.getAddEmailSecondary().get(i).trim())) {
					LOGGER.info(userParams.getAddEmailSecondary().get(i));
					errors.rejectValue("addEmailSecondary",
							"secondary.email.invalid");
				}
				// check if email exits
				List<UserEmail> userEmails = userEmailService.findAll();
				boolean exits = false;

				for (UserEmail temp : userEmails) {
					if (temp.getEmail().equals(
							userParams.getAddEmailSecondary().get(i).trim())) {
						exits = true;
					}
				}
				//
				if (exits) {
					errors.rejectValue("addEmailSecondary",
							"secondary.email.existed");
				}

			}
		}
		// userParams.setAddEmailSecondary(null);

	}
}
